import {base as request, collection} from '../request';
import {resData} from '../request/resData';
import {cloneJson} from "./index";

/**
 * 获取数据源
 * @param formList 表单配置项
 * @param dataSourceApi 数据源接口对象 {url, query, queryFunction}
 * @param query 当前页面的query对象
 * @param preViewFunction   初始化详情对象的字符串函数
 * @param treeSearchKey     首页需要树搜索需要传递key
 * @returns {Promise<unknown>}
 */

export function getServerDataSource(formList, dataSourceApi, query, preViewFunction = '', treeSearchKey = '') {
  let dataSourceApiUrl = '';
  let requestType = 'post';
  let requestMethod = request[requestType];
  console.log(!dataSourceApi, "getServerDataSource")
  if (dataSourceApi) {
    if (typeof dataSourceApi === 'string') {
      dataSourceApiUrl = dataSourceApi;
    } else if (typeof dataSourceApi === 'object') {
      dataSourceApiUrl = dataSourceApi.url;
      if (dataSourceApi.baseUrlType === 'collection') {
        requestMethod = collection[requestType];
      }
    }
  }

  return new Promise((resolve, reject) => {
    dataSourceApiUrl = true
    if (dataSourceApiUrl) {
      // requestMethod(dataSourceApiUrl, dataSourceQuery(dataSourceApi, formList, query))
      //   .then(res => {
          let res = resData;
          let initDataItems = res.data.initDataItems;
          let treeSearchData = [];

          // 处理下拉框选项数据
          if (formList && formList.length > 0) {
            for (let i in formList) {
              if (initDataItems && initDataItems.length > 0) {
                for (let j in initDataItems) {
                  if (formList[i].field === initDataItems[j].name) {
                    if (formList[i].type !== 'modal') {
                      formList[i].options = initDataItems[j].items;
                    }
                  }
                  // 处理树搜索
                  if (treeSearchKey && initDataItems[j].name === treeSearchKey) {
                    treeSearchData = initDataItems[j].items;
                  }
                }
              }
            }
          }

          // 处理下拉框默认值
          let form = res.data.bindDataItem;
          
          form = pretreatmentView(form, preViewFunction);
          if (formList && formList.length > 0) {
            for (let i in formList) {
              if (form) {
                for (let j in form) {
                  if (formList[i].field === j) {
                    formList[i].value = form[j];
                  }
                }
              }
            }
          }

          resolve({formList, treeSearchData, initDataItems, bindDataItem: res.data.bindDataItem});
        // })
        // .catch(err => {
        //   reject(err);
        // });
    } else {
      resolve({formList, treeSearchData: null, bindDataItem: {}, initDataItems: {}});
    }
  });
}


export function dataSourceQuery (dataSourceApi, formList, query) {
  if (dataSourceApi && typeof dataSourceApi === 'object' && dataSourceApi.queryFunction) {
    try{
      let form = {};
      if (formList && formList.length > 0) {
        for (let i in formList) {
          form[formList[i].field] = formList[i].value;
        }
      }
      return new Function('form','query', dataSourceApi.queryFunction)(form, query);
    }catch (e) {
      console.log(e);
    }
  }
  let row = dataSourceApi && typeof dataSourceApi === 'object' && dataSourceApi.query ? cloneJson(dataSourceApi.query) : {};
  if (query && row) {
    for (let i in row) {
      if (typeof row[i] === 'string' && row[i].substr(0, 3) === '$q_' && row[i].length > 3) {
        let field = row[i].substr(3);
        row[i] = query[field];
      }
    }
  }
  return row;
}

export function pretreatmentView (form, preViewFunction) {
  if (preViewFunction && form) {
    return new Function('form', preViewFunction )(form);
  }
  return form;
}

/**
 * 根据formList 生成form
 * @param formList
 * @param query
 * @returns {{}}
 */
export function generateNewForm (formList, query, form) {
  let initForm = {};
  if (formList && formList.length > 0) {
    for (let i in formList) {
      if (initForm[formList[i].field] !== undefined) {
        if (!visibleFunc(formList[i], query, form)) {
          continue;
        }
      }

      if (query) {
        for (let i in formList) {
          if (typeof formList[i].value === 'string' && formList[i].value.substr(0, 3) === '$q_' && formList[i].value.length > 3){
            let field = formList[i].value.substr(3);
            formList[i].value = query[field];
          } else if (query[formList[i].field] !== undefined) {
            formList[i].value = query[formList[i].field];
          }
        }
      }
      if (formList[i].field !== undefined) {
        if (formList[i].type === 'query') {
          if (formList[i].extra && formList[i].extra.queryKey && query) {
            initForm[formList[i].field] = query[formList[i].extra.queryKey];
          }
        } else if(formList[i].type === 'checkbox') {
          initForm[formList[i].field] = formList[i].value !== undefined ? (formList[i].value == 1 ? "10,0" : "10") : [];
        } else {
          // console.log(formList[i].value, 66666)
          initForm[formList[i].field] = formList[i].value !== undefined ? formList[i].value : null;
        }
      }
    }
  }
  return initForm;
}

export function changeCheckBoxDefault (form, key) {
  return form[key] == 1 ? [10,0] : [10]
}

export function visibleFunc (item, query, form) {
  if (item.visibleFunction) {
    let field = item.field;
    try{
      return new Function('form','field', 'query', item.visibleFunction )(form, field, query);
    }catch(e) {
      return true;
    }
  }
  return true;
}

export function getServerDefaultValue (defaultValueApi, formList, query) {
  let defaultValueUrl = defaultValueApi && defaultValueApi.url ? defaultValueApi.url : null;
  return new Promise((resolve, reject) => {
    if (defaultValueUrl) {
      request.post(defaultValueUrl, defaultValueQuery(defaultValueApi, formList, query))
        .then(res => {
          let form = res.data;
          form = pretreatmentView(form);
          if (formList && formList.length > 0) {
            for (let i in formList) {
              if (form) {
                for (let j in form) {
                  if (formList[i].field === j) {
                    formList[i].value = form[j];
                  }
                }
              }
            }
          }
          resolve({formList, data: res.data});
        })
        .catch(err => {
          reject(err);
        });
    } else {
      resolve({formList, data: {}});
    }
  });
}

export function defaultValueQuery (defaultValueApi, formList, query) {
  let row = defaultValueApi && typeof defaultValueApi === 'object' && defaultValueApi.query ? cloneJson(defaultValueApi.query) : {};
  if (row) {
    for (let i in row) {
      if (typeof row[i] === 'string' && row[i].substr(0, 3) === '$q_' && row[i].length > 3) {
        let field = row[i].substr(3);
        if (query[field] !== undefined) {
          row[i] = query[field];
        }
      }
    }
  }
  return row;
}
